interface EndgamePosition {
  pieces: {
    type: string
    color: 'white' | 'black'
    position: { row: number, col: number }
  }[]
  evaluation: number
  bestMove?: {
    from: { row: number, col: number }
    to: { row: number, col: number }
  }
}

export function useEndgameDB() {
  // 基本终局数据库
  const endgamePositions: EndgamePosition[] = [
    // 王和兵对王
    {
      pieces: [
        { type: 'king', color: 'white', position: { row: 6, col: 4 } },
        { type: 'pawn', color: 'white', position: { row: 6, col: 3 } },
        { type: 'king', color: 'black', position: { row: 7, col: 4 } }
      ],
      evaluation: 5,
      bestMove: {
        from: { row: 6, col: 4 },
        to: { row: 5, col: 4 }
      }
    },
    // 王车对王
    {
      pieces: [
        { type: 'king', color: 'white', position: { row: 7, col: 4 } },
        { type: 'rook', color: 'white', position: { row: 0, col: 0 } },
        { type: 'king', color: 'black', position: { row: 0, col: 4 } }
      ],
      evaluation: 8,
      bestMove: {
        from: { row: 0, col: 0 },
        to: { row: 0, col: 1 }
      }
    }
    // 可以添加更多终局位置
  ]

  const countPieces = (board: (string | null)[][]): number => {
    let count = 0
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        if (board[row][col]) count++
      }
    }
    return count
  }

  const matchPosition = (
    board: (string | null)[][],
    position: EndgamePosition
  ): number => {
    let score = 0
    for (const piece of position.pieces) {
      const boardPiece = board[piece.position.row][piece.position.col]
      if (!boardPiece) return 0
      
      const [color, type] = boardPiece.split('-')
      if (color === piece.color && type === piece.type) {
        score++
      }
    }
    return score / position.pieces.length
  }

  const findBestMove = (
    board: (string | null)[][],
    color: 'white' | 'black'
  ): { from: { row: number, col: number }, to: { row: number, col: number } } | null => {
    // 只在棋子数量少于6个时使用终局数据库
    if (countPieces(board) > 6) return null

    let bestMatch = 0
    let bestPosition: EndgamePosition | null = null

    for (const position of endgamePositions) {
      const matchScore = matchPosition(board, position)
      if (matchScore > bestMatch) {
        bestMatch = matchScore
        bestPosition = position
      }
    }

    if (bestMatch > 0.8 && bestPosition?.bestMove) {
      return bestPosition.bestMove
    }

    return null
  }

  return {
    findBestMove
  }
} 